<div class="row gap-20 masonry pos-r">
	<div class="masonry-sizer col-md-12"></div>
	<div class="masonry-item col-md-6">
		<div class="bgc-white p-20 bd">
			<h6 class="c-grey-900" th:text="#{alarm.admin.title.new}">Nueva Alarma</h6>
			<div class="mT-30">
				<form id="alarmForm" th:object="${alarmform}"
					th:action="@{/savealarm}" method="post">
					<input type='hidden' class='primarykey' id="idAlarm"
						th:field="*{idAlarm}">
					
					<input type='hidden' id="degradedConcat"
						th:field="*{degradedConcat}">
					<input type='hidden' id="downConcat"
						th:field="*{downConcat}">
					
					<div class="form-row">
						<div class="form-group col-md-12">
							<label for="name" th:text="#{form.alarm.name}"></label> <span id="name_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span> 
							<input type="text" class="form-control" id="name" th:field="*{name}" required>
						</div>
						
					</div>
					<div class="form-row">
						<div class="form-group col-md-12"><label for="blockedTime"
							th:text="#{form.alarm.blockedTime}"></label> <span id="blockedTime_span" class="badge bgc-red-50 c-red-700 p-10 lh-0 tt-c badge-pill"></span>
							<input type="number"
							step="1" class="form-control" id="blockedTime"
							th:field="*{blockedTime}" required></div>
					</div>
					
					<div class="form-row">
						<div class="form-group col-md-12">
							<label for="emailsDegraded" th:text="#{form.alarm.emailsDegraded}"></label>
							<select class="select2 col-md-12" id="emailsDegraded" th:field="*{emailsDegraded}" required multiple="multiple"> 
								<option th:each="t: ${emailsDegradeds}" th:value="${t.idMail}"
									th:text="${t.emailAddress}">
								</option>
						</select></div>
					</div>
					
					<div class="form-row">
						<div class="form-group col-md-12">
							<label for="emailsDown" th:text="#{form.alarm.emailsDown}"></label>
							<select class="select2 col-md-12" id="emailsDown" th:field="*{emailsDown}" required multiple="multiple"> 
								<option th:each="t: ${emailsDowns}" th:value="${t.idMail}"
									th:text="${t.emailAddress}">
								</option>
						</select></div>
					</div>
					
					<button id="alarmBtn" type="submit" class="btn btn-primary" th:text="#{button.save}">Guardar</button>
					<button id="cleanBtn" class="btn btn-primary" onclick="cleanForm('#alarmForm');" th:text="#{button.cleanForm}">Limpiar formulario</button>
				</form>
			</div>
		</div>
	</div>
	<div class="masonry-item col-md-6">
		<div class="bgc-white bd bdrs-3 p-20 mB-20">
			<h4 class="c-grey-900 mB-20" th:text="#{table.alarm.title}"></h4>
			<table id="alarmTable" class="table table-striped table-bordered"
				cellspacing="0" width="100%">
				<thead>
					<tr>
						<th></th>
						<th th:text="#{table.alarm.name}"></th>
						<th th:text="#{table.alarm.blockedTime}"></th>
					</tr>
				</thead>
			</table>
		</div>
	</div>
</div>

<script th:inline="javascript">

$(document).ready(function() {
	
	$('.select2').select2();
	
	// Gestión de las datatables
	var actionSaveAlarm = /*[[@{/savealarm}]]*/;
	var actionEmails = /*[[@{/emails}]]*/; 
	var actionDeleteAlarm = /*[[@{/deletealarm}]]*/;
	var getAlarms = /*[[@{/alarmsdatatable}]]*/;
	
	var tblAlarm = $('#alarmTable').DataTable({
		dom: 'Bfrtip',
	    select: 'single',
	    responsive: true,
	    altEditor: true,
	    buttons: [{extend: 'selected',text: 'Editar',name: 'editPageForm',
	    	action: function ( e, dt, node, config ) {
				// Para el action 'Editar' obtenemos los valores de la fila seleccioanda
				// directamente y los copiamos al formulario
				for (var o = dt, a = [], e = 0; e < o.context[0].aoColumns.length; e++) a.push({
	                id: o.context[0].aoColumns[e].mData,
	            	title: o.context[0].aoColumns[e].sTitle                
	            });
				var d = dt.rows({
                    selected: !0
                })
                
                var idAlarm = d.data()[0][a[0].id]
				var name = d.data()[0][a[1].id]
				var blockedTime = d.data()[0][a[2].id]
                
				$.ajax(actionEmails,{
					data:$.param({'id':idAlarm, 'type':0}),
					type:'GET',
					success: function(data){
						$('#emailsDegraded').select2().val(data).trigger('change');
					},
					error:function(){
						$('#alarmForm').append('<div id="errorModalAlarm" class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.mailDegraded}]] + '</strong></div>');
					}
				});
				
				$.ajax(actionEmails,{
					data:$.param({'id':idAlarm, 'type':1}),
					type:'GET',
					success: function(data){
						$('#emailsDown').select2().val(data).trigger('change');
					},
					error:function(){
						$('#alarmForm').append('<div id="errorModalAlarm" class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.mailDown}]] + '</strong></div>');
					}
				});
				
                $("#idAlarm").val(idAlarm);
                $("#name").val(name);
                $("#blockedTime").val(blockedTime);
			}
	    }, {extend: 'selected',text: 'Eliminar',name: 'delete'}],
	
	    "iTotalRecords": "totalElements",
        "iTotalDisplayRecords": "numberOfElements",
	    
		"processing": true,
	    "serverSide": true,
		"ajax": {
	        "url": getAlarms,
	        "dataSrc" : "data",
	        "data": function (data) {
	        	// Datos a pasar al modal
	            data.formId = "alarmForm";
	        }
	      },
	    "language": {
	        "url": "js/datatables/i18n/spanish.json",
	        select: {
	            rows: {
	                _: "%d filas seleccionadas",
	                1: "1 fila seleccionada"
	            }
	          }
	        },
		"columns": [
	        { "data": "idAlarm",
	          "visible": false},
	        { "data": "name" },
	        { "data": "blockedTime" }
	        ]
		}).on('crudaction', function(e, accion, idAlarm, data, rowindex){
		    // e          Evento Jquery
		    // accion     [add|edit|delete]
		    // pkid       Primer campo en la data [id]                ... en add,    retorna null
		    // data       Los campos adicionales  [campo_1, campo_n]  ... en delete, retorna null
		    // rowindex   El index de la fila para el dataTable       ... en add,    retorna null
		    
		    $('#altEditor-modal .modal-body .alert').remove();
		    // Se muestra la capa 'cargando...'
		    loading();
		    
		    switch(accion){
		        case 'delete':
		        	var type = $('form[name="altEditor-form"] input').attr('id');
		        	if (type == 'idAlarm'){
		        		$.ajax(actionDeleteAlarm,{
			            	data:$.param({'id':idAlarm, 'index':rowindex}),
			                type:'POST',
			                success: function(data){
			                    
			                	if (data == "-1" && $('#errorModalMail').length == 0){
			                		$('#alarmForm').append('<div id="errorModalAlarm" class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.inUse}]] + '</strong></div>');
			                	}else{
									$('#errorModalAlarm').remove();
								}
			                	
			                	$('#emailsDegraded option').each(function() {
			                	    if ( $(this).val() == data.index ) {
			                	        $(this).remove();
			                	    }
			                	});
			                	
			                	$('#emailsDown option').each(function() {
			                	    if ( $(this).val() == data.index ) {
			                	        $(this).remove();
			                	    }
			                	});
			                	
			                	// Se oculta la capa 'cargando...'
			                	hide();
			                    tblAlarm.row(data.index).remove().draw();
			                    
			                    $('#altEditor-modal .modal-body .alert').remove();
			                    $('#altEditor-modal').modal('hide');
			                },
			                error:function(){}
			            });
		        	}else{
						// Se oculta la capa 'cargando...'
						hide();
					}
		            break;
		        default:
		            $('#altEditor-modal .modal-body .alert').remove();
		            $('#altEditor-modal .modal-body').append('<div class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.NotAuthorized}]] + '</strong></div>');
		            break;
		    }
		});
	
	  $( "#alarmBtn" ).click(function( event ) {
		  event.preventDefault();
		  
		  var numDegraded =  $("#emailsDegraded").select2('data').length;
		  var numDown =  $("#emailsDown").select2('data').length;
		  var newEmailDegraded = "";
		  var newEmailDown = "";

		  for (var i=0; i<numDegraded; i++){
		    newEmailDegraded += $("#emailsDegraded").select2('data')[i].id;
		    if (i!=numDegraded-1){
		  	  newEmailDegraded += "&";
		    }
		  }

		  for (var j=0; j<numDown; j++){
		    newEmailDown += $("#emailsDown").select2('data')[j].id;
		    if (j!=numDown-1){
		  	  newEmailDown += "&";
		    }
		  }

		  $("#alarmForm input")[1].value = newEmailDegraded;
		  $("#alarmForm input")[2].value = newEmailDown;
		  
		  var formData = JSON.stringify($("#alarmForm").serializeJSON());
		  var url = /*[[@{/savealarm}]]*/;
		  
		  loading();
		  if ($('#alarmForm')[0].checkValidity() === false) {
			  hide();
			  
			  $('#alarmForm *').filter(':input').each(function(){
	      	    
		          if(!$(this)[0].checkValidity()){
		      	   	$("#" + $(this).attr('id')).addClass("has-error");
		      	  } else {
		      	   	$("#" + $(this).attr('id')).removeClass("has-error");
		      	  }
	      	    
	      	  });
			  
			  if ($("#emailsDegraded").select2('data').length == 0){
				  $('#errorModalAlarm2').remove();
				  $('#alarmForm').append('<div id="errorModalAlarm2" class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.oneMailDegraded}]] + '</strong></div>');
			  }else{
				  $('#errorModalAlarm2').remove();
			  }
			  
			  if ($("#emailsDown").select2('data').length == 0){
				  $('#errorModalAlarm3').remove();
				  $('#alarmForm').append('<div id="errorModalAlarm3" class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.oneMailDown}]] + '</strong></div>');
			  }else{
				  $('#errorModalAlarm3').remove();
			  }
			  
		  } else{
			  $.ajax({
				  type: "POST",
				  url: url,
				  data: formData,
				  success: function(data, error){
					  var errores = JSON.parse(data.error);
					  
					  if (data.error != null){
						  jQuery.each(errores, function(i, val) {
						  	$('#alarmForm *').filter('span').each(function(){
								if (i == $(this).attr('id')){
									$("#" + i).text(val);
								}
							});
						  });
					  }else{
						  $("#alarmForm")[0].reset();
						  
						  $('#alarmForm *').filter('span').each(function(){
								$(this).text('');
							});
						$("#alarmForm select").select2().val('').change();
					  }
					  
					  hide();
					  tblAlarm.row.add($(data.data)).draw(false);
					  
					   $('#alarmForm *').filter(':input').each(function(){
						 $("#" + $(this).attr('id')).removeClass("has-error");
					   });
					   
					   if ($('#errorModalAlarm').length > 0){
						 $('#errorModalAlarm').remove();
					   }
					   if ($('#errorModalAlarm2').length > 0){
						 $('#errorModalAlarm2').remove();
					   }
					   if ($('#errorModalAlarm3').length > 0){
						 $('#errorModalAlarm3').remove();
					   }
					  
				  },
				  error:function(){
					  hide();
					  $('#alarmForm').append('<div id="errorModalAlarm" class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.sameName}]] + '</strong></div>');
				  },
				  dataType: "json",
				  contentType : "application/json"
				});
		  }
	  
	});
		
});

function cleanForm(f){
	$(f + ' *').filter(':input').each(function(){
		$(this).val('');
	});
	$(f + ' *').filter('span').each(function(){
		$(this).text('');
	});
	$(f + " select").select2().val('').change();
	$(f).find(".alert").remove();
}

</script>